import { ApiResponse } from '../types';

// 缓存数据接口
interface CacheData {
    data: ApiResponse<any>;
    timestamp: number;
    expiresAt: number;
    cardContent: string;
}

// 卡片数据缓存管理器（内存版本）
class CardCacheManager {
    private readonly CACHE_EXPIRY_HOURS = 24; // 24小时过期
    private cacheMap = new Map<string, CacheData>(); // 使用Map替代localStorage
    private pendingRequests = new Map<string, Promise<ApiResponse<any>>>(); // 跟踪进行中的请求

    // 生成缓存key
    private generateCacheKey(cardContent: string): string {
        // 简单hash函数，将cardContent转换为固定长度的字符串
        let hash = 0;
        for (let i = 0; i < cardContent.length; i++) {
            const char = cardContent.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        return `card_${Math.abs(hash)}`;
    }

    // 检查缓存是否有效
    private isCacheValid(cacheData: CacheData): boolean {
        return Date.now() < cacheData.expiresAt;
    }

    // 获取缓存数据
    getCache(cardContent: string): ApiResponse<any> | null {
        try {
            const cacheKey = this.generateCacheKey(cardContent);
            const cacheData = this.cacheMap.get(cacheKey);

            if (!cacheData) {
                return null;
            }

            if (!this.isCacheValid(cacheData)) {
                // 缓存过期，删除无效缓存
                this.removeCache(cardContent);
                return null;
            }

            return cacheData.data;
        } catch (error) {
            console.error('读取卡片缓存失败:', error);
            return null;
        }
    }

    // 设置缓存数据
    setCache(cardContent: string, data: ApiResponse<any>): void {
        try {
            const cacheKey = this.generateCacheKey(cardContent);
            const now = Date.now();
            const expiresAt = now + (this.CACHE_EXPIRY_HOURS * 60 * 60 * 1000);

            const cacheData: CacheData = {
                data,
                timestamp: now,
                expiresAt,
                cardContent: cardContent.substring(0, 100) // 存储前100个字符用于调试
            };

            this.cacheMap.set(cacheKey, cacheData);
        } catch (error) {
            console.error('设置卡片缓存失败:', error);
        }
    }

    // 删除指定缓存
    removeCache(cardContent: string): void {
        try {
            const cacheKey = this.generateCacheKey(cardContent);
            this.cacheMap.delete(cacheKey);
        } catch (error) {
            console.error('删除卡片缓存失败:', error);
        }
    }

    // 清理所有过期缓存
    cleanExpiredCache(): void {
        try {
            let expiredCount = 0;

            for (const [key, cacheData] of this.cacheMap.entries()) {
                if (!this.isCacheValid(cacheData)) {
                    this.cacheMap.delete(key);
                    expiredCount++;
                }
            }
        } catch (error) {
            console.error('清理过期卡片缓存失败:', error);
        }
    }

    // 获取缓存统计信息
    getCacheStats(): { totalCaches: number; validCaches: number; expiredCaches: number } {
        try {
            let validCaches = 0;
            let expiredCaches = 0;

            for (const cacheData of this.cacheMap.values()) {
                if (this.isCacheValid(cacheData)) {
                    validCaches++;
                } else {
                    expiredCaches++;
                }
            }

            return {
                totalCaches: this.cacheMap.size,
                validCaches,
                expiredCaches
            };
        } catch (error) {
            console.error('获取缓存统计失败:', error);
            return { totalCaches: 0, validCaches: 0, expiredCaches: 0 };
        }
    }

    // 检查是否有相同的请求正在进行
    hasPendingRequest(cardContent: string): boolean {
        const cacheKey = this.generateCacheKey(cardContent);
        return this.pendingRequests.has(cacheKey);
    }

    // 获取正在进行的请求
    getPendingRequest(cardContent: string): Promise<ApiResponse<any>> | null {
        const cacheKey = this.generateCacheKey(cardContent);
        return this.pendingRequests.get(cacheKey) || null;
    }

    // 添加正在进行的请求
    addPendingRequest(cardContent: string, requestPromise: Promise<ApiResponse<any>>): void {
        const cacheKey = this.generateCacheKey(cardContent);
        this.pendingRequests.set(cacheKey, requestPromise);

        // 请求完成后清理
        requestPromise.finally(() => {
            this.pendingRequests.delete(cacheKey);
        });
    }

    // 清理所有缓存和待处理请求
    clearAll(): void {
        this.cacheMap.clear();
        this.pendingRequests.clear();
    }
}

// 创建缓存管理器实例
const cardCacheManager = new CardCacheManager();

// 定期清理过期缓存（每60分钟）
setInterval(() => {
    cardCacheManager.cleanExpiredCache();
}, 60 * 60 * 1000);

// 通用卡片相关API
const CARD_API_BASE = '/langchain-backend/card';

function isNotEmptyObject(obj: any): boolean {
    return (
        typeof obj === 'object' &&
        Object.keys(obj).length > 0
    );
}

export const cardApi = {
    // 根据基金名称获取卡片数据（带缓存机制和请求防重）
    getCardByCardContent: async (cardContent: string): Promise<ApiResponse<any>> => {
        try {
            // 1. 检查缓存
            const cachedData = cardCacheManager.getCache(cardContent);
            if (cachedData && cachedData.data && cachedData.data.data && (
                (cachedData.data.type === 'line' && cachedData.data.data.length > 0) ||
                (cachedData.data.type === 'product' && isNotEmptyObject(cachedData.data.data))
            )) {
                return cachedData;
            }

            // 2. 检查是否有相同的请求正在进行
            const pendingRequest = cardCacheManager.getPendingRequest(cardContent);
            if (pendingRequest) {
                return await pendingRequest;
            }

            // 3. 创建新的请求
            const input = cardContent;

            const requestPromise = (async (): Promise<ApiResponse<any>> => {
                const response = await fetch(CARD_API_BASE, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ input })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                const result: ApiResponse<any> = { success: true, data };

                // 缓存成功的响应数据
                cardCacheManager.setCache(cardContent, result);

                return result;
            })();

            // 4. 将请求添加到待处理列表
            cardCacheManager.addPendingRequest(cardContent, requestPromise);

            return await requestPromise;
        } catch (error) {
            console.error('获取卡片数据失败:', error);
            const errorResult: ApiResponse<any> = {
                success: false,
                error: error instanceof Error ? error.message : '获取卡片数据失败'
            };

            // 注意：不缓存错误响应，确保下次可以重新尝试
            return errorResult;
        }
    },

    // 清除指定内容的缓存
    clearCache: (cardContent: string): void => {
        cardCacheManager.removeCache(cardContent);
    },

    // 清理所有过期缓存
    cleanExpiredCache: (): void => {
        cardCacheManager.cleanExpiredCache();
    },

    // 获取缓存统计信息
    getCacheStats: () => {
        return cardCacheManager.getCacheStats();
    },

    // 清理所有缓存（新增方法）
    clearAllCache: (): void => {
        cardCacheManager.clearAll();
    }
};

// 导出缓存管理器以便外部使用
export { CardCacheManager }; 